package com.yida.gwj.expend.service.impl;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.exception.ServiceException;
import com.yida.gwj.api.domain.GwjConfBusinessFlag;
import com.yida.gwj.api.domain.GwjConfStep;
import com.yida.gwj.api.domain.GwjFinanceAccountMain;
import com.yida.gwj.api.domain.request.RemoteGwjFinanceAccountMainRequest;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.api.service.RemoteGwjExpendService;
import com.yida.gwj.common.domain.mq.MqSendResult;
import com.yida.gwj.common.enums.GwjBusinessFlagType;
import com.yida.gwj.common.enums.GwjBusinessLogResult;
import com.yida.gwj.common.enums.GwjCheckAccountStatus;
import com.yida.gwj.common.enums.StepConfigInfoEnum;
import com.yida.gwj.common.handler.MqSendMessageHandler;
import com.yida.gwj.common.utils.GwjEnumUtils;
import com.yida.gwj.expend.annotation.ConfStepConfigCheck;
import com.yida.gwj.expend.config.MaintenanceFundsBusinessConfiguration;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusiness;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessAttachment;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessBuild;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessCommunity;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessHouse;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessInfo;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessLog;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessOwner;
import com.yida.gwj.expend.domain.dto.AllocatedAmountListDTO;
import com.yida.gwj.expend.domain.dto.AllocatedAmountSelectDTO;
import com.yida.gwj.expend.domain.dto.Application4ApprovalDTO;
import com.yida.gwj.expend.domain.dto.ApplicationReportDTO;
import com.yida.gwj.expend.domain.dto.Appropriate4ApproveDTO;
import com.yida.gwj.expend.domain.dto.ChangeSchemeDTO;
import com.yida.gwj.expend.domain.dto.ConfirmReceiptDTO;
import com.yida.gwj.expend.domain.dto.FilingCertificateDTO;
import com.yida.gwj.expend.domain.dto.GwjMaintenanceFundsBusinessGetInfoDTO;
import com.yida.gwj.expend.domain.dto.GwjMaintenanceFundsBusinessListDTO;
import com.yida.gwj.expend.domain.dto.OneTimeNotificationDTO;
import com.yida.gwj.expend.domain.dto.StepConfigInfoDTO;
import com.yida.gwj.expend.domain.dto.TotalCostShareListDTO;
import com.yida.gwj.expend.domain.message.MaintenanceFundsMqMessageBody;
import com.yida.gwj.expend.domain.message.PreAcceptMessage;
import com.yida.gwj.expend.domain.message.PreAcceptSubmitMessage;
import com.yida.gwj.expend.domain.request.AllocatedAmountRequest;
import com.yida.gwj.expend.domain.request.BusinessProcessRequest;
import com.yida.gwj.expend.domain.request.EditFormRequest;
import com.yida.gwj.expend.domain.request.GwjMaintenanceFundsBusinessListRequest;
import com.yida.gwj.expend.domain.request.HousesUnderBuildRequest;
import com.yida.gwj.expend.domain.request.SubmitRequest;
import com.yida.gwj.expend.enums.AppropriationWayEnum;
import com.yida.gwj.expend.enums.BusinessAttachmentServerTypeEnum;
import com.yida.gwj.expend.enums.BusinessServerStatusEnum;
import com.yida.gwj.expend.enums.BusinessStatusEnum;
import com.yida.gwj.expend.enums.BusinessTypeEnum;
import com.yida.gwj.expend.enums.FlagStatusEnum;
import com.yida.gwj.expend.enums.MaintenanceFundsErrorEnum;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessAppropriateService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessAttachmentService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessBuildService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessCommunityService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessHouseService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessInfoService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessLogService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessOwnerService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessUrgentService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;

/**
 * 公维金维修资金业务Service业务层处理
 *
 * @author lgp
 * @date 2023-02-20
 */
@Service
public class GwjMaintenanceFundsBusinessUrgentServiceImpl implements IGwjMaintenanceFundsBusinessUrgentService {

    private final Logger log = LoggerFactory.getLogger(GwjMaintenanceFundsBusinessUrgentServiceImpl.class);

    @Autowired
    private MqSendMessageHandler mqSendMessageHandler;
    @Autowired
    private IGwjMaintenanceFundsBusinessService maintenanceFundsBusinessService;
    @Autowired
    private MaintenanceFundsBusinessConfiguration maintenanceFundsBusinessConfiguration;
    @Autowired
    private RemoteGwjConfigService remoteGwjConfigService;
    @Autowired
    private IGwjMaintenanceFundsBusinessAppropriateService maintenanceFundsBusinessAppropriateService;
    @Autowired
    private IGwjMaintenanceFundsBusinessInfoService maintenanceFundsBusinessInfoService;
    @Autowired
    private IGwjMaintenanceFundsBusinessLogService maintenanceFundsBusinessLogService;
    @Autowired
    private IGwjMaintenanceFundsBusinessHouseService maintenanceFundsBusinessHouseService;
    @Autowired
    private IGwjMaintenanceFundsBusinessBuildService maintenanceFundsBusinessBuildService;
    @Autowired
    private IGwjMaintenanceFundsBusinessOwnerService maintenanceFundsBusinessOwnerService;
    @Autowired
    private IGwjMaintenanceFundsBusinessCommunityService maintenanceFundsBusinessCommunityService;
    @Autowired
    private IGwjMaintenanceFundsBusinessAttachmentService maintenanceFundsBusinessAttachmentService;

    @Autowired
    private RemoteGwjExpendService remoteGwjExpendService;

    @Override
    public GwjMaintenanceFundsBusinessGetInfoDTO getInfoDetails(Long businessId) {
        return maintenanceFundsBusinessService.getInfoDetails(businessId);
    }

    @Override
    public List<GwjMaintenanceFundsBusinessListDTO> getGwjMaintenanceFundsBusinessList(GwjMaintenanceFundsBusinessListRequest maintenanceFundsBusinessListRequest) {
        return maintenanceFundsBusinessService.getGwjMaintenanceFundsBusinessList(maintenanceFundsBusinessListRequest);
    }

    @Override
    public int takeParts(BusinessProcessRequest businessProcessRequest) {
        return maintenanceFundsBusinessService.takeParts(businessProcessRequest);
    }

    @Override
    public AllocatedAmountSelectDTO allocatedAmountSelect(AllocatedAmountRequest allocatedAmountRequest) {
        return maintenanceFundsBusinessService.allocatedAmountSelect(allocatedAmountRequest);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int preAcceptExamine(Long bizId) {
        Optional.ofNullable(maintenanceFundsBusinessService.delete4Save((businessId) -> {
            PreAcceptSubmitMessage preAcceptSubmitMessage = maintenanceFundsBusinessService.getBusinessModules(businessId);
            GwjMaintenanceFundsBusiness maintenanceFundsBusiness = preAcceptSubmitMessage.getMaintenanceFundsBusiness();
            maintenanceFundsBusiness.setBizFlagId(GwjBusinessFlagType.EXPEND_URGENT_FORMAL.getCode());
            try {
                R<GwjConfStep> r = remoteGwjConfigService.getFirstStep(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
                if (R.isError(r)) {
                    throw new ServiceException(r.getMsg());
                }
                if (ObjectUtil.isNull(r.getData())) {
                    throw new ServiceException(r.getMsg());
                }
                maintenanceFundsBusiness.setStepId(r.getData().getStepId());
            } catch (Exception e) {
                log.error("远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]异常,异常信息: [{}]", e);
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_EXAMINE) + "远程调用 -> [remoteGwjConfigService][getFirstStep]异常");
            }
            try {
                R<GwjConfBusinessFlag> r = remoteGwjConfigService.selectGwjConfBusinessFlagByBizFlagId(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
                if (R.isError(r)) {
                    throw new ServiceException(r.getMsg());
                }
                if (ObjectUtil.isNull(r.getData())) {
                    throw new ServiceException("远程调用获取配置失败");
                }
                maintenanceFundsBusiness.setFlowId(r.getData().getFlowId());
            } catch (Exception e) {
                log.error("远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常,异常信息: [{}]", e);
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_EXAMINE) + "远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常");
            }
            maintenanceFundsBusiness.setBizId(null);
            maintenanceFundsBusiness.setCreateTime(DateTime.now());
            maintenanceFundsBusiness.setUpdateTime(DateTime.now());
            maintenanceFundsBusiness.setCreateBy(maintenanceFundsBusiness.getCreateBy());
            maintenanceFundsBusiness.setUpdateBy(maintenanceFundsBusiness.getCreateBy());
            maintenanceFundsBusiness.setStatus(BusinessStatusEnum.SUBMIT.getCode());
            maintenanceFundsBusiness.setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
            maintenanceFundsBusiness.setOutServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            maintenanceFundsBusiness.setServerIdentification(IdUtil.getSnowflakeNextIdStr());
            maintenanceFundsBusiness.setType(BusinessTypeEnum.URGENT_FORMAL.getCode());
            maintenanceFundsBusiness.setCurrentOperId(null);
            maintenanceFundsBusiness.setCurrentOperName(null);
            return Optional.of(preAcceptSubmitMessage);
        }, bizId).<ServiceException>orElseThrow(() -> {
            throw new ServiceException("delete4Save异常");
        }));
        try {
            PreAcceptMessage preAcceptMessage = maintenanceFundsBusinessService.preAcceptExamine(bizId);
            String tag = maintenanceFundsBusinessConfiguration.urgentTagProperties().getPreAcceptExamine();
            MqSendResult mqSendResult = mqSendMessageHandler.syncSend(new MaintenanceFundsMqMessageBody() {
                {
                    setJsonMsg(JSONUtil.toJsonStr(preAcceptMessage));
                    setServerIdentification(preAcceptMessage.getServerIdentification());
                }
            }, new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessUrgentSendRequest(tag, null));
            if (mqSendResult.isSuccess()) {
                return FlagStatusEnum.SUC.getCode();
            } else {
                throw new ServiceException("[公维金资金应急申请]预受理审核异常");
            }
        } catch (ServiceException e) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_EXAMINE) + e.getMessage());
        }
    }

    @Override
    public int preAcceptRetreat(BusinessProcessRequest businessProcessRequest) {
        return maintenanceFundsBusinessService.preAcceptRetreat(businessProcessRequest);
    }

    @Override
    public StepConfigInfoDTO getStepConfigInfo(GwjBusinessFlagType... businessFlagTypes) {
        return maintenanceFundsBusinessService.getStepConfigInfo(businessFlagTypes);
    }

    @Override
    public List<GwjMaintenanceFundsBusinessHouse> allocatedAmountCancelList(AllocatedAmountRequest allocatedAmountRequest) {
        return maintenanceFundsBusinessService.allocatedAmountCancelList(allocatedAmountRequest);
    }

    @Override
    public ChangeSchemeDTO getTransformationPlan(Long businessId) {
        return maintenanceFundsBusinessService.getTransformationPlan(businessId);
    }

    @Override
    public ApplicationReportDTO getApplicationReport(Long businessId) {
        return maintenanceFundsBusinessService.getApplicationReport(businessId);
    }

    @Override
    public int confirmAcceptance(SubmitRequest submitRequest) {
        System.out.println("1:" + submitRequest);
        return maintenanceFundsBusinessService.confirmAcceptance(submitRequest);
    }

    @ConfStepConfigCheck(bizId = "#submitRequest.bizId", stepConfigInfo = {StepConfigInfoEnum.SUBMIT})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int submit(SubmitRequest submitRequest) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessService.selectGwjMaintenanceFundsBusinessByBusinessId(submitRequest.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "GwjMaintenanceFundsBusiness为空");
        }
        if (ObjectUtil.notEqual(maintenanceFundsBusiness.getStatus(), submitRequest.getStatus())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "业务状态不一致,请重新提交");
        }
        BusinessStatusEnum statusEnum;
        BusinessStatusEnum oldStatusEnum = BusinessStatusEnum.transfer(submitRequest.getStatus());
        GwjMaintenanceFundsBusinessInfo gwjMaintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(maintenanceFundsBusiness.getBizId());
        switch (oldStatusEnum) {
            // 1.受理阶段需要确认是否收件
            case TAKE_PARTS:
                try {
                    if (ObjectUtil.equal(BusinessTypeEnum.FORMAL.getCode(), maintenanceFundsBusiness.getType())) {
                        List<BusinessAttachmentServerTypeEnum> noServerTypeEnum = maintenanceFundsBusinessAttachmentService.checkNull(() -> {
                            List<GwjMaintenanceFundsBusinessAttachment> maintenanceFundsBusinessAttachmentList = maintenanceFundsBusinessAttachmentService.selectGwjMaintenanceFundsBusinessAttachmentList(new GwjMaintenanceFundsBusinessAttachment() {
                                {
                                    setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                                }
                            });
                            return Optional.of(maintenanceFundsBusinessAttachmentList);
                        }, true, BusinessAttachmentServerTypeEnum.getUrgentServerTypeList());
                        if (CollectionUtil.isNotEmpty(noServerTypeEnum)) {
                            throw new ServiceException("附件" + noServerTypeEnum.get(0).getInfo() + "未收件,请先确认收件");
                        }
                    }
                    if (ObjectUtil.equal(BusinessTypeEnum.URGENT_FORMAL.getCode(), maintenanceFundsBusiness.getType())) {
                        List<BusinessAttachmentServerTypeEnum> noServerTypeEnum = maintenanceFundsBusinessAttachmentService.checkNull(() -> {
                            List<GwjMaintenanceFundsBusinessAttachment> maintenanceFundsBusinessAttachmentList = maintenanceFundsBusinessAttachmentService.selectGwjMaintenanceFundsBusinessAttachmentList(new GwjMaintenanceFundsBusinessAttachment() {
                                {
                                    setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                                }
                            });
                            return Optional.of(maintenanceFundsBusinessAttachmentList);
                        }, true, BusinessAttachmentServerTypeEnum.getUrgentServerTypeList());
                        if (CollectionUtil.isNotEmpty(noServerTypeEnum)) {
                            throw new ServiceException("附件" + noServerTypeEnum.get(0).getInfo() + "未收件,请先确认收件");
                        }
                    }
                } catch (Exception e) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + e.getMessage());
                }
                statusEnum = BusinessStatusEnum.FIRST_INSTANCE;
                // ---------------------------20230904取消步骤回调 s--------------------------------------
                // 发送外网步骤回调
                // String takePartsJsonMsg = maintenanceFundsBusinessService.resultNotify(maintenanceFundsBusiness);
                // if (ObjectUtil.isEmpty(takePartsJsonMsg)) {
                // throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                // }
                // // 步骤回调修改为远程调用
                // try {
                // remoteGwjExpendService.resultNotify(takePartsJsonMsg, SecurityConstants.INNER).getData();
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // ---------------------------20230904取消步骤回调 e--------------------------------------
                break;
            // 2.初审提交阶段
            case FIRST_INSTANCE:
                statusEnum = BusinessStatusEnum.REEXAMINE;
                // ---------------------------20230904取消步骤回调 s--------------------------------------
                // 发送外网步骤回调
                // String firstInstanceJsonMsg = maintenanceFundsBusinessService.resultNotify(maintenanceFundsBusiness);
                // if (ObjectUtil.isEmpty(firstInstanceJsonMsg)) {
                // throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                // }
                // // 步骤回调修改为远程调用
                // try {
                // remoteGwjExpendService.resultNotify(firstInstanceJsonMsg, SecurityConstants.INNER).getData();
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // ---------------------------20230904取消步骤回调 e--------------------------------------
                break;
            // 3.复审提交阶段（一次拨付跳过财务对账流程）
            case REEXAMINE:
                if (ObjectUtil.equal(AppropriationWayEnum.TWO.getCode(), gwjMaintenanceFundsBusinessInfo.getAppropriationWay())) {
                    if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), maintenanceFundsBusiness.getFinancialJournalFlag())) {
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "请先生成财务流水");
                    }
                    statusEnum = BusinessStatusEnum.FINANCE_CHECK;
                } else {
                    statusEnum = BusinessStatusEnum.FINISH;
                    // 一次拨付直接办理结束
                    R<GwjConfStep> gwjConfStepR = remoteGwjConfigService.selectNextGwjConfStepByFlagId(maintenanceFundsBusiness.getBizFlagId(), maintenanceFundsBusiness.getStepId(), SecurityConstants.INNER);
                    if (R.isError(gwjConfStepR)) {
                        throw new ServiceException(gwjConfStepR.getMsg());
                    }
                    if (ObjectUtil.isNull(gwjConfStepR.getData())) {
                        throw new ServiceException(gwjConfStepR.getMsg());
                    }
                    // 当前业务设置为财务对账流程
                    maintenanceFundsBusiness.setStepId(gwjConfStepR.getData().getStepId());
                    // ---------------------------20230904新增步骤回调 s--------------------------------------
                    // 发送外网步骤回调
                    String freexamineJsonMsg = maintenanceFundsBusinessService.resultNotify(maintenanceFundsBusiness);
                    if (ObjectUtil.isEmpty(freexamineJsonMsg)) {
                        throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                    }
                    // 步骤回调修改为远程调用
                    try {
                        remoteGwjExpendService.resultNotify(freexamineJsonMsg, SecurityConstants.INNER).getData();
                    } catch (Exception e) {
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) + "支出外网步骤回调一次:" + e.getMessage());
                    }
                    // ---------------------------20230904取消步骤回调 e--------------------------------------
                }
                // ---------------------------20230904取消步骤回调 s--------------------------------------
                // 发送外网步骤回调
                // String freexamineJsonMsg = maintenanceFundsBusinessService.resultNotify(maintenanceFundsBusiness);
                // if (ObjectUtil.isEmpty(freexamineJsonMsg)) {
                // throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                // }
                // // 步骤回调修改为远程调用
                // try {
                // remoteGwjExpendService.resultNotify(freexamineJsonMsg, SecurityConstants.INNER).getData();
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // ---------------------------20230904取消步骤回调 e--------------------------------------
                break;
            // 4、财务对账提交（二次拨付才存在的流程）
            case FINANCE_CHECK:
                if (AppropriationWayEnum.ONE.getCode().equals(gwjMaintenanceFundsBusinessInfo.getAppropriationWay())) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "一次拨付不存在财务对账,请重新提交");
                }
                if (!GwjCheckAccountStatus.CHECK_SUCCESS.getCode().equals(String.valueOf(maintenanceFundsBusiness.getFinanceCheck()))) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "请先完成财务对账");
                }
                statusEnum = BusinessStatusEnum.FINISH;
                // ---------------------------20230906申请阶段二次拨付保留步骤回调 s--------------------------------------
                if (AppropriationWayEnum.TWO.getCode().equals(gwjMaintenanceFundsBusinessInfo.getAppropriationWay())) {
                    // 发送外网步骤回调
                    String financeCheckJsonMsg = maintenanceFundsBusinessService.resultNotify(maintenanceFundsBusiness);
                    if (ObjectUtil.isEmpty(financeCheckJsonMsg)) {
                        throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                    }
                    // 步骤回调修改为远程调用
                    R<Boolean> result = remoteGwjExpendService.resultNotify(financeCheckJsonMsg, SecurityConstants.INNER);
                    if (R.isError(result)) {
                        throw new ServiceException("[财务对账提交]支出外网步骤回调失败1:" + result.getMsg());
                    }
                    if (!result.getData()) {
                        throw new ServiceException("[财务对账提交]支出外网步骤回调失败2:" + result.getMsg());
                    }
                }
                // ---------------------------20230906二次拨付保留步骤回调 e--------------------------------------
                break;
            default:
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "业务状态不一致,请重新提交");
        }
        Long stepId;
        try {
            R<GwjConfStep> r = remoteGwjConfigService.selectNextGwjConfStepByFlagId(maintenanceFundsBusiness.getBizFlagId(), maintenanceFundsBusiness.getStepId(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException(r.getMsg());
            }
            stepId = r.getData().getStepId();
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]异常,异常信息: [{}]", e);
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]异常");
        }
        Optional.ofNullable(maintenanceFundsBusinessService.updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                setStepId(stepId);
                setStatus(statusEnum.getCode());
                setBizId(submitRequest.getBizId());
                setCurrentOperId(submitRequest.getCurrentOperId());
                setCurrentOperName(submitRequest.getCurrentOperName());
                setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "GwjMaintenanceFundsBusiness更新失败");
        });
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setResult(GwjBusinessLogResult.SUBMIT.getCode());
                setContent(submitRequest.getContent());
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "GwjMaintenanceFundsBusinessLog新增失败");
        }
        // 发送MQ
        if ((ObjectUtil.equal(AppropriationWayEnum.ONE.getCode(), gwjMaintenanceFundsBusinessInfo.getAppropriationWay()) && ObjectUtil.equal(BusinessStatusEnum.REEXAMINE.getCode(), submitRequest.getStatus())) || ((ObjectUtil.equal(AppropriationWayEnum.TWO.getCode(), gwjMaintenanceFundsBusinessInfo.getAppropriationWay()) && ObjectUtil.equal(BusinessStatusEnum.FINANCE_CHECK.getCode(), submitRequest.getStatus())))) {
            insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
                {
                    setBizId(maintenanceFundsBusiness.getBizId());
                    setResult(GwjBusinessLogResult.FINISH.getCode());
                    setAcceptTime(LocalDateTimeUtil.offset(LocalDateTime.now(), 1, ChronoUnit.SECONDS));
                    try {
                        R<GwjConfStep> r = remoteGwjConfigService.getFinalStep(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
                        if (R.isError(r)) {
                            throw new ServiceException(r.getMsg());
                        }
                        if (ObjectUtil.isNull(r.getData())) {
                            throw new ServiceException(r.getMsg());
                        }
                        setStepId(r.getData().getStepId());
                    } catch (Exception e) {
                        log.error("远程调用 -> [remoteGwjConfigService][getFinalStep]异常,异常信息: [{}]", e);
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "远程调用 -> [remoteGwjConfigService][getFinalStep]异常");
                    }
                }
            });
            if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "GwjMaintenanceFundsBusinessLog新增失败");
            }
            reexamine(maintenanceFundsBusiness);
        }
        return FlagStatusEnum.SUC.getCode();
    }

    public int reexamine(GwjMaintenanceFundsBusiness maintenanceFundsBusiness) {
        List<GwjMaintenanceFundsBusinessHouse> maintenanceFundsBusinessHouseList = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessHouseList)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "List<GwjMaintenanceFundsBusinessHouse>为空");
        }
        List<GwjMaintenanceFundsBusinessBuild> maintenanceFundsBusinessBuildList = maintenanceFundsBusinessBuildService.selectGwjMaintenanceFundsBusinessBuildList(new GwjMaintenanceFundsBusinessBuild() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessBuildList)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "List<GwjMaintenanceFundsBusinessBuild>为空");
        }
        List<GwjMaintenanceFundsBusinessOwner> maintenanceFundsBusinessOwnerList = maintenanceFundsBusinessOwnerService.selectGwjMaintenanceFundsBusinessOwnerList(new GwjMaintenanceFundsBusinessOwner() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessOwnerList)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "GwjMaintenanceFundsBusinessOwner为空");
        }
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(maintenanceFundsBusiness.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessCommunity)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "GwjMaintenanceFundsBusinessCommunity为空");
        }
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(maintenanceFundsBusiness.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessInfo)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "GwjMaintenanceFundsBusinessInfo为空");
        }
        PreAcceptSubmitMessage acceptSubmitMessage = new PreAcceptSubmitMessage() {
            {
                setMaintenanceFundsBusiness(maintenanceFundsBusiness);
                setMaintenanceFundsBusinessInfo(maintenanceFundsBusinessInfo);
                setMaintenanceFundsBusinessCommunity(maintenanceFundsBusinessCommunity);
                setMaintenanceFundsBusinessBuildList(maintenanceFundsBusinessBuildList);
                setMaintenanceFundsBusinessHouseList(maintenanceFundsBusinessHouseList);
                setMaintenanceFundsBusinessOwnerList(maintenanceFundsBusinessOwnerList);
            }
        };
        String tag = maintenanceFundsBusinessConfiguration.urgentAppropriateTagProperties().getFormalSubmit();
        MqSendResult mqSendResult = mqSendMessageHandler.syncSend(new MaintenanceFundsMqMessageBody() {
            {
                setJsonMsg(JSONUtil.toJsonStr(acceptSubmitMessage));
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        }, new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessUrgentAppropriateSendRequest(tag, null));
        if (mqSendResult.isSuccess()) {
            return FlagStatusEnum.SUC.getCode();
        } else {
            log.error("资金申请正式受理MQ消息发送异常 -> [{}]", mqSendResult.getMessage());
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "资金申请正式受理MQ消息发送异常");
        }
    }

    @Override
    public int confirmReceipt(ConfirmReceiptDTO confirmReceipt) {
        return maintenanceFundsBusinessService.confirmReceipt(confirmReceipt);
    }

    @Override
    public int cancelReceipt(Long attachmentId) {
        return maintenanceFundsBusinessService.cancelReceipt(attachmentId);
    }

    @Override
    public int fallback(SubmitRequest submitRequest) {
        return maintenanceFundsBusinessService.fallback(submitRequest);
    }

    @Override
    public OneTimeNotificationDTO oneTimeNotification(Long businessId) {
        return maintenanceFundsBusinessService.oneTimeNotification(businessId);
    }

    @Override
    public int editForm(EditFormRequest editFormRequest) {
        return maintenanceFundsBusinessService.editForm(editFormRequest);
    }

    @Override
    public Application4ApprovalDTO getApplication4Approval(Long bizId) {
        return maintenanceFundsBusinessService.getApplication4Approval(bizId);
    }

    @Override
    public List<GwjMaintenanceFundsBusinessBuild> getSelectBuilds(Long bizId) {
        return maintenanceFundsBusinessService.getSelectBuilds(bizId);
    }

    @Override
    public List<GwjMaintenanceFundsBusinessHouse> getHouseList(HousesUnderBuildRequest housesUnderBuildRequest) {
        return maintenanceFundsBusinessService.getHouseList(housesUnderBuildRequest);
    }

    @Override
    public Appropriate4ApproveDTO getAppropriate4Approval(Long bizId) {
        return maintenanceFundsBusinessService.getAppropriate4Approval(bizId);
    }

    @Override
    public int generateFinancialJournal(Long bizId) {
        return maintenanceFundsBusinessService.generateFinancialJournal(bizId);
    }

    @Override
    public List<GwjFinanceAccountMain> selectGwjFinanceAccountMainList(RemoteGwjFinanceAccountMainRequest mainRequest) {
        return maintenanceFundsBusinessService.selectGwjFinanceAccountMainList(mainRequest);
    }

    @Override
    public List<AllocatedAmountListDTO> exportHouseList(AllocatedAmountRequest allocatedAmountRequest) {
        return maintenanceFundsBusinessService.exportHouseList(allocatedAmountRequest);
    }

    /**
     * 打印备案证明
     *
     * @param bizId 业务标识
     * @return {@link FilingCertificateDTO}
     */
    @Override
    public FilingCertificateDTO printFilingCertificate(Long bizId) {
        return maintenanceFundsBusinessService.printFilingCertificate(bizId);
    }

    /**
     * 查询决算费用分摊清册
     *
     * @param bizId 业务标识
     * @return int
     */
    @Override
    public TotalCostShareListDTO costList(Long bizId) {
        TotalCostShareListDTO totalCostShareListDTO = maintenanceFundsBusinessAppropriateService.costList(bizId, BusinessAttachmentServerTypeEnum.DETAILS_PROJECT_BUDGET_ALLOCATION);
        GwjMaintenanceFundsBusinessInfo gwjMaintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        totalCostShareListDTO.setTotalSettlementAmount(gwjMaintenanceFundsBusinessInfo.getProjectBudgetAmount());
        return totalCostShareListDTO;
    }

    /**
     * 财务对账
     * 
     * @param bizId 业务主键
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean financeCheck(Long bizId) {
        return maintenanceFundsBusinessService.financeCheck(bizId);
    }
}
